/* eslint-disable array-callback-return */
import React from 'react';
import { DownOutlined, PlusOutlined, UpOutlined, QuestionCircleOutlined, DownloadOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Card,
  Button,
  Input,
  DatePicker,
  message,
  Row,
  Col,
  Menu,
  Dropdown,
  Modal,
  Divider,
  Select,
} from 'antd';
import moment from 'moment';
import { connect } from 'dva';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import StandardTable from '@/components/StandardTable';
import Authorized from '@/utils/Authorized';
import { checkPermissions } from '@/utils/authority';
import styles from '@/utils/utils.less';
import downloadFile from '@/utils/utils';
import HOCSelect from '@/components/AntDesign/Select';
import TextOverFlow from '../../components/TextOverFlow';
import Customer from '../../components/Customer';

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { confirm } = Modal;
const { Option } = Select;

@connect(({ publicdata, customer, loading, login }) => ({
  dictCode: publicdata.dictCode,
  pageData: customer.pageData,
  loading: loading.models.customer,
  tabList: customer.tabList,
  stateMap: customer.stateMap,
  expandForm: customer.expandForm,
  activeKey: customer.activeKey,
  formFieldsValue: customer.formFieldsValue,
  respUserList: customer.respUserList,
  assignData: customer.assignData, // 指派数据
  confirmLoading: loading.effects['customer/assignSubmit'],
  login,
  valuesArr: customer.valuesArr,
  supplyList: customer.supplyList,
}))
@Form.create()
class BasicList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      formValues: {},
      selectedRowKeys: [],
      selectedRows: [],
      modalVisible: false,
    };
    this.columns = [
      {
        title: '客户编号',
        dataIndex: 'no',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '客户名称',
        dataIndex: 'name',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '统一社会信用代码',
        dataIndex: 'uniCreditCode',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '签约方',
        dataIndex: 'suppName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val || '--',
      },
      {
        title: '负责人',
        dataIndex: 'primName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
      },
      {
        title: '创建时间',
        dataIndex: 'creTime',
        sorter: (a, b) => new Date(b.creTime) - new Date(a.creTime),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => moment(val).format('YYYY-MM-DD HH:mm'),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <a onClick={e => this.toDetail(e, record.custId)}>查看</a>
            <Divider type="vertical" />
            <Dropdown
              overlay={
                <Menu>
                  {checkPermissions('cs:custInfo:update') && (
                    <Menu.Item key="update" onClick={() => this.updateInfo(record.custId)}>
                      修改
                    </Menu.Item>
                  )}
                  {checkPermissions('cs:custInfo:delete') && (
                    <Menu.Item key="delete" onClick={() => this.delList(record.custId)}>
                      删除
                    </Menu.Item>
                  )}
                </Menu>
              }
            >
              <a>
                更多 <DownOutlined />
              </a>
            </Dropdown>
          </span>
        ),
      },
    ];
  }

  componentDidMount = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'customer/fetchRespUserList',
      payload: {},
    });
    // 获取签约方
    dispatch({
      type: 'customer/getPlatOrAutoSupp',
      payload: { name: null },
    });
    this.getInitialList();
  };

  getInitialList = () => {
    const {
      pageData: { pagination },
      dispatch,
      location,
      formFieldsValue,
    } = this.props;
    if (location.queryParam) {
      dispatch({
        type: 'customer/updateModelData',
        payload: { formFieldsValue: location.queryParam, expandForm: true },
      });
    }

    this.searchList(
      this.processFormData({ ...formFieldsValue }),
      pagination.current,
      pagination.pageSize
    );
  };

  // 点击查询按钮
  searchBtnList = () => {
    const { form, valuesArr, dispatch } = this.props;
    form.validateFieldsAndScroll([...valuesArr], (err, values) => {
      if (!err) {
        dispatch({
          type: 'customer/updateModelData',
          payload: {
            formFieldsValue: values,
          },
        });
        this.searchList(this.processFormData(values));
      }
    });
  };

  // 查询
  searchList = (formFieldsValue, currentPage = 1, pageSize = 10, isClear = true) => {
    if (isClear) {
      this.setState({ selectedRows: [], selectedRowKeys: [] });
    }
    const { dispatch } = this.props;
    const pageArg = { currentPage, pageSize };
    const values = {
      ...formFieldsValue,
      pageArg,
    };

    dispatch({
      type: 'customer/updateModelData',
      payload: {
        values,
      },
    });

    dispatch({
      type: 'customer/fetchList',
      payload: values,
    });

    this.setState({
      formValues: formFieldsValue,
    });
  };

  // 处理form数据
  processFormData = fieldsValue => {
    const formFieldsValue = {};
    const tempFieldsValue = fieldsValue;
    Object.keys(tempFieldsValue).forEach(key => {
      if (key === 'no' || key === 'uniCreditCode') {
        tempFieldsValue[key] = (tempFieldsValue[key] && tempFieldsValue[key].trim()) || null;
      }
      if (key === 'creTime') {
        formFieldsValue.creStartDate = tempFieldsValue.creTime
          ? tempFieldsValue.creTime[0].format('YYYY-MM-DD')
          : null;
        formFieldsValue.creEndDate = tempFieldsValue.creTime
          ? tempFieldsValue.creTime[1].format('YYYY-MM-DD')
          : null;
      }
      formFieldsValue[key] = tempFieldsValue[key] === undefined ? undefined : tempFieldsValue[key];
      delete formFieldsValue.creTime;
    });
    return formFieldsValue;
  };

  // 查询表格布局
  toggleForm = () => {
    const { dispatch, expandForm } = this.props;
    dispatch({
      type: 'customer/updateModelData',
      payload: {
        expandForm: !expandForm,
      },
    });
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = pagination => {
    const { formFieldsValue } = this.props;
    this.searchList(
      this.processFormData(formFieldsValue),
      pagination.current,
      pagination.pageSize,
      false
    );
  };

  // 重置查询
  resetSearch = () => {
    const { dispatch, form } = this.props;
    dispatch({
      type: 'customer/updateModelData',
      payload: {
        formFieldsValue: {},
      },
    });
    form.resetFields();
    form.setFieldsValue({ creTime: null });
  };

  // 删除数据
  delList = custId => {
    this.setState({ selectedRowKeys: [custId] });
    const {
      pageData: { pagination },
      dispatch,
      formFieldsValue,
    } = this.props;
    confirm({
      icon: <QuestionCircleOutlined />,
      title: '你确定要删除此条客户吗？',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      style: { top: 200 },
      onOk: () => {
        dispatch({
          type: 'customer/deleteData',
          payload: { custIds: [custId] },
          callback: res => {
            if (res.success) {
              const selectedLen = 1;
              if (
                pagination.current > 1 &&
                (pagination.total % pagination.pageSize === selectedLen ||
                  pagination.pageSize === selectedLen)
              ) {
                this.searchList(
                  this.processFormData(formFieldsValue),
                  pagination.current - 1,
                  pagination.pageSize
                );
              } else {
                this.searchList(
                  this.processFormData(formFieldsValue),
                  pagination.current,
                  pagination.pageSize
                );
              }
              this.setState({ selectedRowKeys: [] });
              message.success(`${res.message || '删除成功！'}`);
            } else if (Array.isArray(res.data) && res.data.length) {
              const noList = [];
              const dataSource = [];
              res.data.map(r => {
                dataSource.map(c => {
                  if (c.custId === r) {
                    noList.push(c.no);
                  }
                });
              });
              message.warning(
                `客户编号为${noList.join(',')}的客户有合同正在使用，不允许删除，请重新选择`
              );
            } else {
              message.warning(`${res.message || res.data || '删除失败！'}`);
            }
          },
        });
      },
      onCancel: () => {
        this.setState({ selectedRowKeys: [] });
      },
    });
  };

  // 修改启用停用客户状态
  updateStatus = () => {
    const { selectedRowKeys } = this.state;
    const {
      pageData: { pagination },
      dispatch,
      formFieldsValue,
    } = this.props;
    if (selectedRowKeys.length) {
      confirm({
        icon: <QuestionCircleOutlined />,
        title: '你确定要启用/停用这些客户状态吗？',
        okText: '确定',
        okType: 'primary',
        cancelText: '取消',
        style: { top: 200 },
        onOk: () => {
          dispatch({
            type: 'customer/updateState',
            payload: { custIds: selectedRowKeys },
            callback: res => {
              if (res.success) {
                message.success(`${res.message || '启用/停用成功！'}`);
                this.searchList(
                  this.processFormData(formFieldsValue),
                  pagination.current,
                  pagination.pageSize
                );
                this.setState({ selectedRowKeys: [] });
              } else {
                message.warning(`${res.message || '启用/停用失败！'}`);
              }
            },
          });
        },
      });
    } else {
      message.warning('请选择至少一条数据！');
    }
  };

  // 修改信息:客户信息
  updateInfo = custId => {
    router.push(`/salemanage/customer/update?custId=${custId}&activeKey=1`);
  };

  // 查看详情
  toDetail = (e, custId) => {
    e.preventDefault();
    router.push(`/salemanage/customer/detail?custId=${custId}`);
  };

  // 变更客服
  assignModal = () => {
    const { selectedRowKeys, selectedRows } = this.state;
    const {
      login: { baseUser },
    } = this.props;
    const assignFilter = selectedRows.filter(item => item.suppId !== baseUser.suppId);
    const {
      dispatch,
      formFieldsValue,
      pageData: { pagination },
    } = this.props;
    if (assignFilter.length || selectedRowKeys.length === 0) {
      message.warning(
        `线下接单的客户，需要按照负责人下所属签约方的全部客户进行指派（只按签约方进行指派，为将涉及该签约方的所有负责人下的客户进行指派）。`
      );
    }
    if (selectedRowKeys.length > 0) {
      dispatch({
        type: 'customer/getAssignInfo',
        payload: { custIds: selectedRowKeys },
      }).then(response => {
        if (!response.success) {
          this.setState({ modalVisible: false });
        } else {
          this.setState({ modalVisible: true });
        }
      });
    } else {
      const params = {
        pageArg: {
          currentPage: pagination.current,
          pageSize: pagination.pageSize,
        },
        ...formFieldsValue,
      };
      dispatch({
        type: 'customer/getAssignInfo',
        payload: params,
      }).then(response => {
        if (!response.success) {
          this.setState({ modalVisible: false });
        } else {
          this.setState({ modalVisible: true });
        }
      });
    }
  };

  // 指派确定提交
  assignSubmit = () => {
    const { selectedRowKeys } = this.state;
    const {
      dispatch,
      formFieldsValue,
      pageData: { pagination },
      form,
    } = this.props;
    form.validateFields(['assignPrimId'], (err, values) => {
      if (err) return;
      if (selectedRowKeys.length > 0) {
        dispatch({
          type: 'customer/assignSubmit',
          payload: {
            custIds: selectedRowKeys,
            assignPrimId: values.assignPrimId,
          },
        }).then(response => {
          if (response.success) {
            message.success('指派成功');
            this.setState({ modalVisible: false });
            this.searchList(
              this.processFormData(formFieldsValue),
              pagination.current,
              pagination.pageSize
            );
          } else {
            message.warning(response.message || '指派提交数据：服务端错误');
          }
        });
      } else {
        const params = {
          pageArg: {
            currentPage: pagination.current,
            pageSize: pagination.pageSize,
          },
          ...formFieldsValue,
          assignPrimId: values.assignPrimId,
        };
        dispatch({
          type: 'customer/assignSubmit',
          payload: params,
        }).then(response => {
          if (response.success) {
            message.success('指派成功');
            this.setState({ modalVisible: false });
            this.searchList(
              this.processFormData(formFieldsValue),
              pagination.current,
              pagination.pageSize
            );
          } else {
            message.warning(response.message || '指派提交数据：服务端错误');
          }
        });
      }
    });
  };

  // 取消指派弹框
  handleCancle = () => {
    this.setState({
      modalVisible: false,
      selectedRowKeys: [],
      selectedRows: [],
    });
  };

  // 导出数据
  export = () => {
    const { selectedRowKeys } = this.state;
    if (!selectedRowKeys.length) {
      Modal.confirm({
        icon: <QuestionCircleOutlined />,
        title: '温馨提示',
        content: '如果不选择列表数据，则默认导出当前条件下所有数据',
        okText: '导出',
        cancelText: '取消',
        onOk: () => {
          this.exportExcel();
        },
      });
    } else {
      this.exportExcel();
    }
  };

  // 导出excel
  exportExcel = () => {
    const { formValues, selectedRowKeys } = this.state;
    const params = {
      ...formValues,
      custIds: selectedRowKeys,
    };
    downloadFile(params, '/csApi/custInfo/downCust', 'POST');
  };


  render() {
    const { selectedRowKeys, selectedRows, modalVisible } = this.state;
    const {
      pageData,
      loading,
      formFieldsValue,
      expandForm,
      respUserList,
      form: { getFieldDecorator },
      assignData,
      confirmLoading,
      login,
      supplyList,
    } = this.props;
    const formItemLayout = {
      labelCol: { md: { span: 10 } },
      wrapperCol: { md: { span: 14 } },
    };

    // 模态框布局
    const formItemLayoutModal = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
    const renderSimpleForm = (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="客户名称" {...formItemLayout}>
              {getFieldDecorator('custId', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.custId,
              })(<Customer allowClear />)}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <FormItem label="客户编号" {...formItemLayout}>
              {getFieldDecorator('no', {
                rules: [{ required: false, message: '请输入' }],
                initialValue: formFieldsValue.no,
              })(<Input placeholder="请输入" style={{ width: '100%' }} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" onClick={() => this.searchBtnList()}>
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                重置
              </Button>
              <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                展开 <DownOutlined />
              </a>
            </span>
          </Col>
        </Row>
      </Form>
    );
    const renderAdvancedForm = (
      <Form layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="客户名称" {...formItemLayout}>
              {getFieldDecorator('custId', {
                rules: [{ required: false }],
                initialValue: formFieldsValue.custId,
              })(<Customer allowClear />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="客户编号" {...formItemLayout}>
              {getFieldDecorator('no', {
                rules: [{ required: false, message: '请输入' }],
                initialValue: formFieldsValue.no,
              })(<Input placeholder="请输入" style={{ width: '100%' }} />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="统一社会信用代码" {...formItemLayout}>
              {getFieldDecorator('uniCreditCode', {
                rules: [
                  {
                    required: false,
                    message: '18位的数字与字母组合',
                    max: 18,
                    pattern: /^[A-Za-z0-9]{18}$/,
                  },
                ],
                initialValue: formFieldsValue.uniCreditCode,
              })(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="签约方" {...formItemLayout}>
              {getFieldDecorator('suppId', {
                rules: [{ required: false, message: '请选择' }],
                initialValue: formFieldsValue.suppId,
              })(
                <HOCSelect
                  placeholder="请输入关键字检索"
                  {...this.props}
                  showSearch
                  optionFilterProp="children"
                  notFoundContent="暂无数据"
                >
                  {supplyList.map(item => (
                    <Option key={item.suppId} title={item.name} fsOptions={item}>
                      {item.name}
                    </Option>
                  ))}
                </HOCSelect>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="负责人" {...formItemLayout}>
              {getFieldDecorator('primId', {
                rules: [{ required: false, message: '请选择' }],
                initialValue: formFieldsValue.primId,
              })(
                <HOCSelect
                  placeholder="请输入关键字检索"
                  style={{ width: '100%' }}
                  showSearch
                  optionFilterProp="children"
                  allowClear
                >
                  {respUserList.map(item => (
                    <Option key={item.userId} title={item.userName}>
                      {item.userName}
                    </Option>
                  ))}
                </HOCSelect>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="创建时间" {...formItemLayout}>
              {getFieldDecorator('creTime', {
                rules: [{ type: 'array', required: false }],
                initialValue: formFieldsValue.creTime,
              })(
                <RangePicker
                  placeholder={['开始日期', '结束日期']}
                  style={{ width: '100%' }}
                  format="YYYY-MM-DD"
                />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24} />
          <Col md={8} sm={24} />
          <Col md={8} sm={24}>
            <div style={{ overflow: 'hidden' }}>
              <span style={{ float: 'right', marginBottom: 24 }}>
                <Button type="primary" onClick={() => this.searchBtnList()}>
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                  收起 <UpOutlined />
                </a>
              </span>
            </div>
          </Col>
        </Row>
      </Form>
    );
    // 模态框配置
    const modalConfig = {
      title: <span>客户指派</span>,
      visible: modalVisible,
      onOk: this.assignSubmit,
      okText: '确定',
      onCancel: this.handleCancle,
      destroyOnClose: true,
      confirmLoading,
    };
    const renderForm = expandForm ? renderAdvancedForm : renderSimpleForm;
    return (
      <PageHeaderWrapper>
        <Card className={styles.searchCard}>
          <div className={styles.tableListForm}>{renderForm}</div>
        </Card>
        <Card className={styles.tableCard}>
          <Row style={{ marginBottom: 16 }}>
            <Authorized authority="cs:custInfo:insert" noMatch={null}>
              <Button
                type="primary"
                onClick={() => router.push('/salemanage/customer/add')}
                style={{ marginRight: 8 }}
              >
                <PlusOutlined />
                新增
              </Button>
            </Authorized>
            <Authorized authority="cs:custInfo:updateAssign" noMatch={null}>
              {login.baseUser && login.baseUser.postType === 2 ? ( // 管理岗
                <Button style={{ marginRight: 8 }} onClick={() => this.assignModal()}>
                  变更客服
                </Button>
              ) : null}
            </Authorized>
            <Authorized authority="cs:custInfo:uploadCust" noMatch={null}>
              <Button style={{ marginRight: 8 }} onClick={() => router.push('/salemanage/customer/batchadd')}>批量新增</Button>
            </Authorized>
            <Authorized noMatch={null}>
              <Button onClick={this.export}>
                <DownloadOutlined />
                导出
              </Button>
            </Authorized>
          </Row>
          <StandardTable
            selectedRows={selectedRows}
            selectedRowKeys={selectedRowKeys}
            loading={loading}
            data={pageData}
            rowKey="custId"
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </Card>
        <Modal {...modalConfig}>
          <Form layout="horizontal">
            <FormItem {...formItemLayoutModal} label="涉及签约方">
              {getFieldDecorator('suppIdName')(
                <span>{(assignData && assignData.suppContent) || '--'}</span>
              )}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="涉及供应商合同">
              {getFieldDecorator('contName')(
                <span>{(assignData && assignData.contContent) || '--'}</span>
              )}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="当前选择客户">
              {getFieldDecorator('custIdName')(
                <span>{(assignData && assignData.custContent) || '--'}</span>
              )}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="涉及客户负责人">
              {getFieldDecorator('principal')(
                <span>{(assignData && assignData.primContent) || '--'}</span>
              )}
            </FormItem>
            <FormItem {...formItemLayoutModal} label="选择客户负责人">
              {getFieldDecorator('assignPrimId', {
                rules: [{ required: true, message: '请选择' }],
              })(
                <HOCSelect
                  placeholder="请输入关键字检索"
                  style={{ width: '100%' }}
                  showSearch
                  optionFilterProp="children"
                  allowClear
                >
                  {respUserList.map(item => (
                    <Option key={item.userId} title={item.userName}>
                      {item.userName}
                    </Option>
                  ))}
                </HOCSelect>
              )}
            </FormItem>
            <div style={{ lineHeight: '25px', color: 'red', marginLeft: 25 }}>
              <p>
                注：指派业务客户后，会将客户信息及客户对关联的商务合同/供应商合同，报价单以及所有状态的增员数据和涉及账单数据全部迁移至新的负责人下。
              </p>
            </div>
          </Form>
        </Modal>
      </PageHeaderWrapper>
    );
  }
}
const ListSearchForm = Form.create()(BasicList);
export default ListSearchForm;
